package dao

import (
	"context"
	"core/models/entity"
	"core/repo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.uber.org/zap"
)

type AccountDao struct {
	repo *repo.Manager //数据库连接管理器
}

/*
*
插入账户
*/
func (d *AccountDao) SaveAccount(ctx context.Context, ac *entity.Account) error {
	table := d.repo.Mongo.Db.Collection("account")
	_, err := table.InsertOne(ctx, ac)
	if err != nil {
		return err
	}
	return nil
}

/*
*
根据account查询账户
*/
func (d *AccountDao) QueryAccountByAccount(ctx context.Context, ac *entity.Account) *entity.Account {
	account := ac.Account
	filter := bson.M{"account": account}
	var accountEntity entity.Account
	table := d.repo.Mongo.Db.Collection("account")
	err := table.FindOne(context.Background(), filter).Decode(&accountEntity)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			//找不到或者查出来为空
			zap.S().Infof("QueryAccountByAccount empty:%v", err)
			return nil
		}
		zap.S().Errorf("QueryAccountByAccount err:%v", err)
		return nil
	}
	return &accountEntity
}

func NewAccountDao(m *repo.Manager) *AccountDao {
	return &AccountDao{
		repo: m,
	}
}
